package com.example.vaccine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.vaccine.VO.PageVO;
import com.example.vaccine.VO.ResultVO;
import com.example.vaccine.controller.configuration.FileUploadConfig;
import com.example.vaccine.entity.CheckTasks;
import com.example.vaccine.entity.Users;
import com.example.vaccine.form.LoginForm;
import com.example.vaccine.mail.Mail;
import com.example.vaccine.mapper.CheckTasksMapper;
import com.example.vaccine.mapper.UsersMapper;
import com.example.vaccine.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.vaccine.util.ResultVOUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Coisn
 * @since 2025-06-12
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private CheckTasksMapper checkTasksMapper;

    @Autowired
    private FileUploadConfig fileUploadConfig;

    @Value("${avatar.upload.dir}")
    private String uploadDir; // 在 yml 配置，例如 D:/学习文档/大三/区块链应用开发/vaccine/vaccine/vaccine/src/main/resources/static/avatar

    @Override
    public List<Users> getCheckers() {
        return usersMapper.selectCheckers();
    }

    @Override
    public PageVO getUserPage(String name, String role, int page, int size) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();

        if (name != null && !name.trim().isEmpty()) {
            wrapper.like("name", name);
        }

        if (role != null && !role.trim().isEmpty()) {
            wrapper.like("role", role);
        }

        Page<Users> pageRequest = new Page<>(page, size);
        Page<Users> resultPage = this.page(pageRequest, wrapper);

        PageVO pageVO = new PageVO();
        pageVO.setData(resultPage.getRecords());
        pageVO.setTotal(resultPage.getTotal());
        return pageVO;
    }

    @Override
    public ResultVO login(LoginForm loginForm, HttpServletRequest request) {
        ResultVO resultVO = new ResultVO();

        // 1. 验证码校验
        String sessionCaptcha = (String) request.getSession().getAttribute("verifyCode");
        if (sessionCaptcha == null || loginForm.getCaptcha() == null ||
                !sessionCaptcha.equalsIgnoreCase(loginForm.getCaptcha())) {
            resultVO.setCode(-3);
            return resultVO;
        }

        // 2. 根据手机号查询用户
        if (loginForm.getPhone() == null || loginForm.getPhone().trim().isEmpty()) {
            resultVO.setCode(-4);
            return resultVO;
        }

        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", loginForm.getPhone().trim());
        Users user = this.usersMapper.selectOne(queryWrapper);

        if (user == null) {
            resultVO.setCode(-1);
            return resultVO;
        }

        // 3. 校验密码（这里建议后续使用加密算法）
        if (loginForm.getPassword() == null || !user.getPassword().equals(loginForm.getPassword())) {
            resultVO.setCode(-2);
            return resultVO;
        }

        // 4. 设置默认头像
        if (StringUtils.isEmpty(user.getAvatar())) {
            switch (user.getRole()) {
                case "admin": user.setAvatar("/avatar/default-admin.png"); break;
                case "doctor": user.setAvatar("/avatar/default-doctor.png"); break;
                case "checker": user.setAvatar("/avatar/default-checker.png"); break;
                default: user.setAvatar("/avatar/default.png"); break; // 可设置默认默认头像
            }
        }

        // 5. 登录成功
        resultVO.setCode(0);
        resultVO.setData(user);

        return resultVO;
    }


    public void sendEmailReminderByTaskId(Integer taskId) throws Exception {
        CheckTasks task = checkTasksMapper.selectById(taskId);
        if (task == null) {
            throw new Exception("任务不存在");
        }
        if (!"pending".equalsIgnoreCase(task.getStatus())) {
            throw new Exception("任务状态不是 pending");
        }

        Users checker = usersMapper.selectById(task.getCheckerId());
        if (checker == null || checker.getEmail() == null) {
            throw new Exception("核查员不存在或邮箱为空");
        }

        String toEmail = checker.getEmail();
        String subject = "核查任务提醒";
        String content = String.format(
                "<h3>尊敬的核查员 %s，您好！</h3>" +
                        "<p>您有一条核查任务（任务ID：%d，疫苗编号：%s）当前状态为 <b>pending</b>，请尽快处理。</p>" +
                        "<p>感谢您的配合！</p>",
                checker.getName(), task.getId(), task.getVaccineNumbering()
        );

        Mail mail = new Mail();
        mail.sendMail(subject, content, toEmail);
    }

    @Override
    public String uploadAvatar(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IOException("上传文件为空");
        }

        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        // 创建目标路径
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        File dest = new File(dir, fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 返回 Web 可访问路径，例如 /avatar/xxx.jpg
        return "/avatar/" + fileName;
    }

    @Override
    public boolean updateAvatar(Integer userId, String avatarPath) {
        Users user = usersMapper.selectById(userId);
        if (user == null) return false;
        user.setAvatar(avatarPath);
        return usersMapper.updateById(user) > 0;
    }

    @Override
    public ResultVO handleAvatarUpload(Integer userId, MultipartFile file) {
        try {
            // 1. 上传文件并返回访问路径
            String avatarPath = this.uploadAvatar(file);

            // 2. 更新数据库
            boolean updated = this.updateAvatar(userId, avatarPath);
            if (!updated) {
                return ResultVOUtil.fail();
            }

            return ResultVOUtil.success(avatarPath);
        } catch (Exception e) {
            return ResultVOUtil.fail();
        }
    }


    @Override
    public String getAvatarByUserId(Integer userId) {
        Users user = usersMapper.selectById(userId);
        return user != null ? user.getAvatar() : null;
    }
}
